import { createStore } from '../redux';
// 导入reducers
import rootReducer from './reducers';
// 创建store
// let store = createStore(rootReducer);

function compose(...fns) {
    return function(args) {
        return fns.reduceRight((args, fn) => {
            return fn(args);
        }, args);
    }
}

// 应用中间件（采用分层的思想）
function applyMiddleware(...middlewares) {
    return function (createStore) {
        return function(reducer) {
            let store = createStore(reducer);
            let dispatch;
            let middlewareAPI = {
                getState: store.getState,
                dispatch: (action) => dispatch(action)
            }
            let chain = middlewares.map(middleware => middleware(middlewareAPI));
            dispatch = compose(...chain)(store.dispatch);
            // 重写dispatch方法
            return {
                ...store,
                dispatch
            }
        }
    }
}

// 在调用dispatch(action)的前后做一些事
function logger({ getState, dispatch }) {
    return function(next) {
        return function (action) {
            console.log('prev todo...');
            next(action);
            console.log('next todo...');
        }
    }
}

// 支持action传入的是函数
function thunk({ getState, dispatch }) {
    return function(next) {
        return function (action) {
            if (typeof action === 'function') {
                return action(dispatch, getState);
            }
            return next(action);
        }
    }
}

// 支持action传入promise
function promise({ getState, dispatch }) {
    return function(next) {
        return function(action) {
            if (typeof action.then === 'function') {
                return action.then(newAction => dispatch(newAction))
            }
            return next(action);
        }
    }
}

// 创建store
let store = applyMiddleware(promise, thunk, logger)(createStore)(rootReducer);

export default store;
